package com.ds.map_set.leetcode;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Dianzhi Han
 * @version 1.0
 * @description: TODO
 * @date 2022/10/9 9:07
 */
public class Num290_WordPattern {
    // pattern = "abba", str = "dog cat cat dog"
    public boolean wordPattern(String pattern, String s) {
        String[] str = s.split(" ");
        if (str.length != pattern.length()) {
            // pattern = "abba" str = "dog cat cat"
            return false;
        }
        // 建立pattern和str关于数字的映射关系
        int count = 1;
        Map<String,Integer> map1 = new HashMap<>();
        StringBuilder sb1 = new StringBuilder();
        for (String temp : str) {
            if (map1.containsKey(temp)) {
                sb1.append(map1.get(temp));
            }else {
                map1.put(temp,count);
                sb1.append(count ++);
            }
        }
        count = 1;
        Map<Character,Integer> map2 = new HashMap<>();
        StringBuilder sb2 = new StringBuilder();
        // pattern = "abba"
        for (int i = 0; i < pattern.length(); i++) {
            char c = pattern.charAt(i);
            if (map2.containsKey(c)) {
                sb2.append(map2.get(c));
            }else {
                map2.put(c,count);
                sb2.append(count ++);
            }
        }
        // 1221   1221
        return sb1.toString().equals(sb2.toString());
    }
}
